<?php

class Event extends AppModel {

	var $name = 'Event';

	//The Associations below have been created with all possible keys, those that are not needed can be removed
	var $belongsTo = array(
			'Organization' =>
				array('className' => 'Organization'
				),
			'Calendar' =>
				array('className' => 'Calendar'
				),
	);
	
	

	var $hasAndBelongsToMany = array('Tag');


	function findEvents($url=array(), $organization_id=null) {
		$organization_condition = ($organization_id)?" AND `Event`.organization_id = ".$organization_id:"";
		$events = $this->findAll(array('YEAR(date)='.$url['year'].' AND MONTH(date)='.$url['month'].$organization_condition),null,null,null,null,2);
		if ($url['tag'] != 'all') {
			$events = $this->findEventsByTag($events,$url['tag']);
		}
		
		if ($url['calendar'] != 'all' && $url['tag'] == 'all') {
			$events = $this->findEventsByCalendar($events,$url['calendar']);
		}
		return $events;
	}
	
	function findEventsByTag($events=array(),$tag=null) {
		$output = array();
		if (!$events) { 
			return null; 
		} else {
			$x = 0;
			foreach ($events as $event) {
				for ($i = 0; $i < count($event['Tag']); $i++) {
					if ($event['Tag'][$i]['shortname'] == $tag) {
						$output[$x] = $event;
						$x++;
					}
				}
			}
			if (!$output) { 
				return null; 
			} else {
				return $output;
			}
		}
	}
	
	function findEventsByCalendar($events=array(),$calendar) {
		$output = array();
		if (!$events) {
			return null;
		} else {
			$x = 0;
			foreach ($events as $event) {
				$calendar_found = false;
				if ($event['Event']['calendar_id'] == $calendar) {
					$output[$x] = $event;
					$x++;
				}
			}
			return $output;
		}
	}

	function findPublicEvents($url=array(), $organization_id=null) {
		$organization_condition = ($organization_id)?" AND `Event`.public = 1 AND `Event`.organization_id = ".$organization_id:"";
		$events = $this->findAll(array('YEAR(date)='.$url['year'].' AND MONTH(date)='.$url['month'].$organization_condition),null,null,null,null,2);
		if ($url['tag'] != 'all') {
			$events = $this->findEventsByTag($events,$url['tag']);
		}
		
		if ($url['calendar'] != 'all' && $url['tag'] == 'all') {
			$events = $this->findEventsByCalendar($events,$url['calendar']);
		}
		return $events;
	}

}
